package com.wp.targetOffer;

/**
 * Created by 王萍 on 2017/7/28 0028.
 */
public class 重建二叉树 {

    public static void main(String[] args) {

        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
        reConstructBinaryTree(pre, in);
    }

    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        return constructCore(pre, 0, pre.length - 1, in, 0, in.length - 1);
    }

    public static TreeNode constructCore(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {

        TreeNode root = new TreeNode(pre[preStart]);
        int rootOrder = inStart;
        while (in[rootOrder] != pre[preStart] && rootOrder <= preEnd) {
            ++rootOrder;
        }

        int leftLength = rootOrder - inStart;
        if (leftLength > 0) {
            root.left = constructCore(pre, preStart + 1, preStart + leftLength, in, inStart, rootOrder - 1);
        }

        if (preEnd - preStart > leftLength) {
            root.right = constructCore(pre, preStart + leftLength + 1, preEnd, in, rootOrder + 1, inEnd);
        }
        return root;
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
